package cn.jee.controller;


import cn.jee.entity.Order;
import cn.jee.entity.Product;
import cn.jee.entity.User;
import cn.jee.repository.OrderRepository;
import cn.jee.repository.ProductRepository;
import cn.jee.repository.UserRepository;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Optional;

@Controller
public class CartController {

  @Autowired
  private UserRepository userRepository;
  @Autowired
  private ProductRepository productRepository;
  @Autowired
  private OrderRepository orderRepository;

  @GetMapping("/cart/add")
  public String addToCart(@RequestParam("productId") Long productId,
                          @RequestParam("username") String username) {

    User user = userRepository.findByUsername(username);
    Product product = productRepository.findById(productId).orElseThrow();

    // 查找是否已有购物车
    Order order = orderRepository.findByUserAndSubmitted(user, false)
      .orElseGet(() -> {
        Order newOrder = new Order();
        newOrder.setUser(user);
        newOrder.setSubmitted(false);
        newOrder.setTotalPrice(0.0);
        return orderRepository.save(newOrder);
      });

    order.getProducts().add(product);
    orderRepository.save(order);

    return "redirect:/cart?username=" + username;
  }

  // 文件名：CartController.java（继续添加）
//  @GetMapping("/cart")
//  public String viewCart(@RequestParam("username") String username, Model model) {
//    User user = userRepository.findByUsername(username);
//    Optional<Order> optionalOrder = orderRepository.findByUserAndSubmitted(user, false);
//
//    if (optionalOrder.isPresent()) {
//      Order cart = optionalOrder.get();
//      model.addAttribute("products", cart.getProducts());
//      model.addAttribute("cartExists", true);
//      model.addAttribute("username", username);
//    } else {
//      model.addAttribute("cartExists", false);
//    }
//
//    return "cart";
//  }
  @GetMapping("/cart")
  public String viewCart(@RequestParam("username") String username,
                         Model model,
                         HttpSession session) {
    User user = userRepository.findByUsername(username);
    session.setAttribute("user", user); // 确保session中有user
    model.addAttribute("user", user); // 确保model中有user

    Optional<Order> optionalOrder = orderRepository.findByUserAndSubmitted(user, false);

    if (optionalOrder.isPresent()) {
      Order cart = optionalOrder.get();
      model.addAttribute("products", cart.getProducts());
      model.addAttribute("cartExists", true);
      model.addAttribute("username", username);
    } else {
      model.addAttribute("cartExists", false);
    }

    return "cart";
  }
  // 文件名：CartController.java（继续添加）
  @PostMapping("/cart/submit")
  public String submitCart(@RequestParam("username") String username) {
    User user = userRepository.findByUsername(username);
    Optional<Order> optionalOrder = orderRepository.findByUserAndSubmitted(user, false);

    if (optionalOrder.isPresent()) {
      Order cart = optionalOrder.get();
      double total = cart.getProducts().stream()
        .mapToDouble(Product::getPrice)
        .sum();
      cart.setTotalPrice(total);
      cart.setSubmitted(true);
      orderRepository.save(cart);
    }

    return "redirect:/products?username=" + username;
  }

}
